<?php
namespace Home\Model;
use Think\Model;
class UserModel extends Model
{
    protected $insertFields = 'username,password,cpassword,chkcode';
    // 注册时使用的规则
    protected $_validate = array(
        array('chkcode', 'require', '验证码不能为空！', 1),
        array('chkcode', 'chkcode', '验证码输入不正确！', 1, 'callback'),
        array('username', 'require', '用户名不能为空！', 1),
        array('password', 'require', '密码不能为空！', 1),
        array('cpassword', 'password', '两次密码输入不一致！', 1, 'confirm'),
        array('username', '', '该用户名已经存在！', 1, 'unique'),
    );
    // 登录时使用的规则
    public $_login_validate = array(

        array('username', 'require', '用户名不能为空！', 1),
        array('password', 'require', '密码不能为空！', 1),
    );
    protected function chkcode($code)
    {
        $verify = new \Think\Verify();
        return $verify->check($code);
    }
    protected function _before_insert(&$data, $option)
    {
        $data['password'] = md5($data['password']);
    }
    public function login()
    {
//        $username = $this->username;
//        $password = $this->password;
        $username = $_POST['username'];
        $password = $_POST['password'];
        $user = $this->where("phone=$username OR user_name=$username")->find();
        if($user)
        {
            if($user['passwd'] == md5($password))
            {
                session('id', $user['id']);
                session('username', $user['username']);
                // 把购物车中的数据移动到数据库中
//                $cart = D('cart');
//                $cart->moveDataToDb();
                return TRUE;
            }
            else
            {
                $this->error = '密码不正确！';
                return FALSE;
            }
        }
        else
        {
            $this->error = '账号不存在！';
            return FALSE;
        }
    }
}